package com.aliyun.tiangong.util;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Objects;
import java.util.Set;

/**
 * @author xinghen
 * @ClassName: BeanValidateUtil
 * @Package: com.xinghen.common.core.utils
 * @Description 参数校验工具
 * @create 2018-04-11 16:05
 */
public class BeanValidateUtil {

    private static Validator validator = Validation.byProvider(HibernateValidator.class)
            .configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 参数校验
     *
     * @param t
     * @param <T>
     */
    public static <T> void validate(T t) {
        if (Objects.isNull(t)) {
            return;
        }
        Set<ConstraintViolation<T>> violations = validator.validate(t);
        if (CollectionUtils.isNotEmpty(violations)) {
            ConstraintViolation<T> violation = violations.iterator().next();
            throw new RuntimeException(violation.getMessage());
        }
    }

}
